package com.mgface.springdata.controller;

import com.mgface.springdata.entity.Article;
import com.mgface.springdata.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project springdataCollection
 * @create 2018-08-17 15:21
 **/
@RestController
public class MongodbController {
    @Autowired
    private MongoTemplate template;
    @Autowired
    ArticleRepository articleRepository;

    @GetMapping("/select")
    public Map<String, Object> select() {
        Page<Article> page = articleRepository.myQuery("zhangsan", new PageRequest(0, 10, Sort.Direction.ASC, "name"));
        List<Article> list = page.getContent();
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        map.put("count", page.getTotalPages());
        return map;
    }

    @GetMapping("/selectAll")
    public List<Article> add() {
        Query query = new Query();
        Criteria criteria = Criteria.where("name").is("admin123");
        query.addCriteria(criteria);

        Pageable pageable = new PageRequest(0, 2, Sort.Direction.ASC, "name");
        query.with(pageable);
        return template.find(query, Article.class);
    }
}
